package il.technion.cs236369.webserver.typeHandlers;

import il.technion.cs236369.interfaces.ICookie;
import il.technion.cs236369.interfaces.IObserver;
import il.technion.cs236369.interfaces.ISession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class CookieManager {
	private final Map<ICookie, ISession>	map	= new ConcurrentHashMap<ICookie, ISession>();
	private Long							i	= 0L;

	/**
	 * Gets the session associated with the cookie
	 * 
	 * @param cookie The cookie that identifies the session
	 * @return An existing session identified with the cookie; will return null
	 *         if cookie is null, or no session is associated with the cookie
	 */
	public ISession getSession(ICookie cookie) {
		if (cookie == null) {
			return null;
		}
		return map.get(cookie);
	}

	/**
	 * Generates a new cookie and a session tied to the cookie
	 * 
	 * @return The new cookie generated
	 */
	public ICookie generateNewCookie() {
		long cookieId;
		synchronized (i) {
			cookieId = i;
			i++;
		}

		final ICookie result = new CookieImpl(cookieId);
		SessionImpl session = new SessionImpl();
		session.setObservable(new IObserver() {
			// when invalidated, remove the cookie from the CM
			@Override
			public void notifyObserver() {
				map.remove(result);
			}
		});
		map.put(result, session);
		return result;
	}
}
